import requests
from PIL import Image, ImageDraw, ImageFont


def get_amap_coordinate(locations, url="https://restapi.amap.com/v3/assistant/coordinate/convert", output='json',
                        key='8d78b9850672ca403fd01682e91ba9b2', coordsys='gps'):
    params = {
        'output': output,
        'locations': locations,
        'key': key,
        'coordsys': coordsys
    }
    response = requests.get(url, params=params)
    # 检查请求是否成功
    if response.status_code == 200:
        # 解析JSON数据
        data = response.json()
        status = data.get("status", "0")
        if status == '1':
            # 提取formatted_addres
            locations = data.get("locations")
            return locations
    else:
        return f"Request failed with status code {response.status_code}"


def get_regeo_address(location, url="https://restapi.amap.com/v3/geocode/regeo", output='json',
                      key='8d78b9850672ca403fd01682e91ba9b2', radius='1', extensions='base'):
    params = {
        'output': output,
        'location': location,
        'key': key,
        'radius': radius,
        'extensions': extensions
    }
    # 发送请求
    response = requests.get(url, params=params)
    # 检查请求是否成功
    if response.status_code == 200:
        # 解析JSON数据
        data = response.json()
        return data.get("regeocode", {})
    else:
        return f"Request failed with status code {response.status_code}"


def get_nominatim_address(lon, lat, zoom=18, addressdetails=1, format='json'):
    params = {
        'format': format,
        'lon': lon,
        'lat': lat,
        'zoom': zoom,
        'addressdetails': addressdetails
    }
    headers = {
        'User-Agent': 'YourAppName/1.0 (your-email@example.com)'  # 替换为你的应用名称和邮箱
    }
    # 发送请求
    response = requests.get('https://nominatim.openstreetmap.org/reverse', params=params,headers=headers)
    # 检查请求是否成功
    if response.status_code == 200:
        # 解析JSON数据
        data = response.json()
        return data
    else:
        return f"Request failed with status code {response.status_code}"


def add_text_to_image(image_path, text, output_path, font_path='STXINWEI.TTF'):
    # 打开图像
    image = Image.open(image_path)

    # 获取图像尺寸
    width, height = image.size

    # 动态设置字体大小
    font_size = min(width, height) // 20

    # 加载支持Unicode的字体
    font = ImageFont.truetype(font_path, font_size)

    # 计算文字区域高度
    text_height = font_size + 20  # 假设文字区域高度为字体大小加上20像素的内边距

    # 创建一个新的图像，增加底部高度
    new_image_height = height + text_height
    new_image = Image.new("RGB", (width, new_image_height), (255, 255, 255))

    # 将原图像粘贴到新图像的顶部
    new_image.paste(image, (0, 0))

    # 在新图像底部添加文字
    draw = ImageDraw.Draw(new_image)
    text_position = (10, height + 10)  # 新图像底部位置，稍微向上移动一些以避免边界
    draw.text(text_position, text, font=font, fill="black")

    # 保存新的图像
    new_image.save(output_path)
